package com.xatz.scanner

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isGone
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.xatz.ksoap2_android.SoapEnvelope
import com.xatz.ksoap2_android.serialization.SoapObject
import com.xatz.ksoap2_android.serialization.SoapSerializationEnvelope
import com.xatz.ksoap2_android.transport.HttpTransportSE
import com.xatz.scanner.bean.CheckWeightCarBean
import com.xatz.scanner.databinding.ActivityArrivalConfirmationBinding
import com.xatz.scanner.databinding.ItemCarNumberInfoBinding
import okhttp3.internal.filterList
import timber.log.Timber
import java.util.concurrent.Executors

/**
 * Created by tdq on 2022/1/17.
 */
class ArrivalConfirmCheckWeightActivity : AppCompatActivity(),
    CarNumberInfoCheckWeightAdapter.OnItemClickListener {

    private var mBinding: ActivityArrivalConfirmationBinding? = null

    private val mThreadPool = Executors.newCachedThreadPool()

    private val mCarInfoBeans = mutableListOf<CheckWeightCarBean>()

    private var searchText = ""

    private val adapter = CarNumberInfoCheckWeightAdapter(mCarInfoBeans)

    private val netProgressDialog by lazy { NetProgressDialog(this) }

    private val userBz: String by lazy {
        getSharedPreferences(
            Constant.configName,
            Context.MODE_PRIVATE
        ).getString(Constant.userBz, "").toString()
    }

    private val activityLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == Activity.RESULT_OK) {
                initData()
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityArrivalConfirmationBinding.inflate(layoutInflater)
        setContentView(mBinding?.root)
        mBinding?.rvCarInfo?.adapter = adapter
        adapter.setOnItemClickListener(this)
        mBinding?.llSearch?.isGone = true
        initData()
        mBinding?.srlCarNumber?.setOnRefreshListener {
            mCarInfoBeans.clear()
            initData()
        }

    }

    private fun initData() {
        mCarInfoBeans.clear()
        mThreadPool.submit {
            getCarInfoOnNet()
        }
    }

    private fun getCarInfoOnNet() {
        val method = "get_RuChangCL"
        val envolopeVersion = SoapEnvelope.VER11
        val soapAction = "http://tempuri.org/get_RuChangCL"
        val request = SoapObject(Constant.nameSpace, method)
//        if (userBz.startsWith("TK")) {
//            request.addProperty("gongsi", "铸造")
//        } else {
//            request.addProperty("gongsi", "通才")
//        }
        // SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        val envelope = SoapSerializationEnvelope(envolopeVersion)
        envelope.setOutputSoapObject(request)
        envelope.dotNet = true
        val se = HttpTransportSE(Constant.urlCheckWeight)
        try {
            se.call(soapAction, envelope) //envolopeVersion为ver12第一个参数可以为空，必须接口支持ver12才行
            val response = envelope.bodyIn as SoapObject
            //response的处理需要根据返回的具体情况，基本都要进行下面一步
            Timber.e(response.toString())
            val responseSoapObject = response.getProperty("get_RuChangCLResult").toString()
            val checkWeightCarBeans = Gson().fromJson<List<CheckWeightCarBean>>(
                responseSoapObject,
                object : TypeToken<List<CheckWeightCarBean>>() {}.type
            )
            Timber.e(checkWeightCarBeans.size.toString())
            val list = checkWeightCarBeans.filterList {
                if(userBz.startsWith("TK")){
                    gongsi == "铸造"
                }else{
                    gongsi == "通才"
                }
            }
            runOnUiThread {
                if(list.isEmpty()){
                    toast("暂无数据")
                }
                Timber.e(list.toString())
                mCarInfoBeans.addAll(list)
                adapter.notifyDataSetChanged()
                mBinding?.srlCarNumber?.isRefreshing = false
            }

        } catch (e: Exception) {
            e.printStackTrace()
            mBinding?.srlCarNumber?.isRefreshing = false
            toast("暂无数据")
        }
    }

    override fun onItemClick(position: Int) {
        Timber.e(position.toString())
        activityLauncher.launch(
            Intent(
                this,
                ArrivalConfirmationCheckWeightDetailsActivity::class.java
            ).putExtra("CheckWeightCarBean", mCarInfoBeans[position])
        )
    }
}


class CarNumberInfoCheckWeightAdapter(val mCarInfoBeans: MutableList<CheckWeightCarBean>) :
    RecyclerView.Adapter<CarNumberInfoCheckWeightAdapter.CarNumberCheckWeightViewHolder>() {

    class CarNumberCheckWeightViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var tvCarNum: TextView? = null
        var tvPosition: TextView? = null

        init {
            tvCarNum = itemView.findViewById(R.id.tvCarNum)
            tvPosition = itemView.findViewById(R.id.tvPosition)
        }
    }

    private var onItemClickListener: OnItemClickListener? = null

    interface OnItemClickListener {
        fun onItemClick(position: Int)
    }

    fun setOnItemClickListener(onItemClickListener: OnItemClickListener) {
        this.onItemClickListener = onItemClickListener
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): CarNumberCheckWeightViewHolder {
        return CarNumberCheckWeightViewHolder(
            ItemCarNumberInfoBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            ).root
        )
    }

    override fun onBindViewHolder(holder: CarNumberCheckWeightViewHolder, position: Int) {
        holder.tvCarNum?.text = mCarInfoBeans[position].clbm
        holder.tvPosition?.text = (position + 1).toString()
        holder.tvCarNum?.setOnClickListener {
            onItemClickListener?.onItemClick(position)
        }
    }

    override fun getItemCount(): Int {
        return mCarInfoBeans.size
    }
}